<template>
  <div class="login">
    <el-form :model="form" ref="form" :rules="rules" label-width="80px" :inline="false" size="normal">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">登录</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {setToken} from "@/utils/auth";
import {login} from '@/api/user.js'
import {list} from '@/api/menu.js'
import { handleTree} from '@/utils/utils'
import router from '../router'
export default {
  data() {
    return {
      form:{
        username:'',
        password:'',
      },
      rules:{
        username: [{required: true, message: '请输入用户名', trigger: 'change'}],
        password: [{required: true, message: '请输入密码', trigger: 'change'}],
      }
    }
  },
  mounted(){

  },
  computed:{
  },
  methods:{
    onSubmit(formName){
      const that = this
      this.$refs[formName].validate(valid => {
      if (valid) {
        login(this.form.username,this.form.password).then(function(res){
          console.log('res',res);
          if(res.success){
            that.$message.success('登录成功')
            localStorage.setItem('userInfo',JSON.stringify(res.userInfo))
            const token = res.userInfo.access_token
            setToken(token) // 存储token
            list().then(function(res){
              // console.log(res)
              if(res.success){
                let getRouter = handleTree(res.data,'_id')
                localStorage.setItem('menuList',JSON.stringify(getRouter))
                that.$store.dispatch('GenerateRoutes').then(accessRoutes => {
                  that.$router.addRoutes(accessRoutes) // 动态添加可访问路由表
                  that.$router.push('/index')
                })
              }
            }).catch((error)=>{
              console.log(error)
            })
            // that.$router.push('/index')
          }else{
            that.$message.error(res.message)
          }
        })
      } else {
        console.log('error')
      }
      })
      
    }
  },
}
</script>
<style scoped>
  .login{
    width: 600px;
    margin: 100px auto;
  }
</style>
